#include <stdio.h>
#include <stdlib.h>

typedef int bool;

#define true 1;
#define false 0;

struct myList
{
    int * pArr;//头指针
    int length;//最大长度
    int cnt;//有效个数
};

void create_list(struct myList * pList, int length)
{
    pList->pArr = (int *)malloc(sizeof(int) * length);
    if(pList->pArr == NULL){
        printf("内存分配失败\n");
        exit(-1);
    }else{
        pList->length = length;
        pList->cnt = 0;
        printf("创建成功\n");
    }   
    return;
}

bool is_full(struct myList * pList){
    if(pList->length == pList->cnt){
        return true;
    }else{
        return false;
    }
}

int is_empty(struct myList * pList){
    if(pList->cnt == 0){
        return 1;
    }else{
        return 0;
    }
}

bool append(struct myList * pList, int val)
{
    //先判断数组是否已满
    if(is_full(pList)){
        return false;
    }
    pList->pArr[pList->cnt] = val;
    (pList->cnt)++;
    return true;
}

void show_list(struct myList * pList)
{
    if(is_empty(pList)){
        printf("数组为空\n");
    }else{
        printf("show:");
        for(int i = 0;i<pList->cnt;i++){
            printf("%d ",pList->pArr[i]);
        }
    }
}

bool insert(struct myList * pList, int pos, int val)
{
    //先判断数组是否已满
    if(is_full(pList)){
        printf("数组已满，插入失败");
        return false;
    }
    //判断插入的位置是否合法
    if(pos<1 || pos>pList->cnt+1){
        printf("插入位置有误，插入失败");
        return false;
    }
    //从有效个数的最后一个开始，到输入的下标位置结束，依次往后
    for(int i=pList->cnt-1;i>=pos-1;i--){
        pList->pArr[i+1] = pList->pArr[i];
    }
    pList->pArr[pos-1] = val;
    (pList->cnt)++;
    printf("插入成功\n");
    return true;
}

int delete(struct myList * pList, int pos){

    //判断删除的位置是否合法
    if(pos<1 || pos>pList->cnt+1){
        printf("删除位置有误，删除失败");
        return false;
    }
    int num = pList->pArr[pos-1];
    //从输入的下标位置开始，到有效个数的最后一个结束吗，依次往前
    for(int i=pos;i<=pList->cnt;i++){
        pList->pArr[i-1] = pList->pArr[i];
    };
    pList->cnt--;
    printf("删除成功\n");
    return 1;
}

int main(){
    // struct myList * pList;
    struct myList ml;
    create_list(&ml, 3);
    show_list(&ml);
    append(&ml, 1);
    append(&ml, 2);
    // append(&ml, 3);
    show_list(&ml);
    insert(&ml, 1, 4);
    show_list(&ml);
    delete(&ml, 1);
    show_list(&ml);
}

